import React, { useReducer, useContext } from "react";
const globalContext = React.createContext();
const handle = (preState, action) => {
  let cloneObj = { ...preState };
  switch (action.type) {
    case "changeA":
      cloneObj.name = action.value;
      return cloneObj;
    case "changeB":
      cloneObj.age = action.value;
      return cloneObj;
    default:
      return cloneObj;
  }
};
const initState = {
  name: "tyy",
  age: 18,
};
export default function App() {
  const [state, dispatch] = useReducer(handle, initState);
  return (
    <div>
      <globalContext.Provider value={{ state, dispatch }}>
        <Child1></Child1>
        <Child2></Child2>
        <Child3></Child3>
      </globalContext.Provider>
    </div>
  );
}

function Child1() {
  const { dispatch } = useContext(globalContext);
  return (
    <div>
      <button
        onClick={() => {
          dispatch({
            type: "changeA",
            value: "傻逼",
          });
        }}
      >
        改变2
      </button>
      <button
        onClick={() => [
          dispatch({
            type: "changeB",
            value: 24,
          }),
        ]}
      >
        改变3
      </button>
    </div>
  );
}

function Child2() {
  const { state } = useContext(globalContext);
  return <div>child2---{state.name}</div>;
}

function Child3() {
  const { state } = useContext(globalContext);
  return <div>child3---{state.age}</div>;
}
